<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch" />
    <div class="filter-tags" v-if="hasActiveFilters">
      <span class="filter-label">已选条件：</span>
      <el-tag
        v-if="query.search"
        closable
        @close="clearFilter('search')"
        size="small"
        class="filter-tag"
      >
        关键词: {{ query.search }}
      </el-tag>
      <el-tag
        v-if="query.status"
        closable
        @close="clearFilter('status')"
        size="small"
        class="filter-tag"
        :type="getStatusType(query.status)"
      >
        状态: {{ query.status }}
      </el-tag>
      <el-tag
        v-if="query.category"
        closable
        @close="clearFilter('category')"
        size="small"
        class="filter-tag"
      >
        分类: {{ query.category }}
      </el-tag>
      <el-tag
        v-if="query.condition"
        closable
        @close="clearFilter('condition')"
        size="small"
        class="filter-tag"
      >
        成色: {{ query.condition }}
      </el-tag>
      <el-tag
        v-if="query.minPrice || query.maxPrice"
        closable
        @close="clearPriceFilter()"
        size="small"
        class="filter-tag"
      >
        价格: {{ query.minPrice || "0" }} - {{ query.maxPrice || "不限" }}
      </el-tag>
      <el-button type="primary" link @click="resetFilters" size="small"
        >清空全部</el-button
      >
    </div>
    <div class="container">
      <TableCustom
        :columns="columns"
        :tableData="tableData"
        :total="page.total"
        :viewFunc="handleView"
        :delFunc="handleRemove"
        :changePage="changePage"
        :loading="loading"
      >
        <template #toolbarBtn>
          <el-button type="primary" :icon="Download" @click="exportProducts"
            >导出</el-button
          >
        </template>
        <template #image="scope">
          <template
            v-if="scope.rows && scope.rows.images && scope.rows.images.length > 0"
          >
            <el-image
              :src="scope.rows.images[0]"
              style="width: 50px; height: 50px; border-radius: 4px"
              :preview-src-list="scope.rows.images"
              preview-teleported
              fit="cover"
            />
          </template>
          <template v-else>
            <el-icon style="font-size: 24px; color: #999">
              <IconPicture />
            </el-icon>
          </template>
        </template>
        <template #title="scope">
          <div v-if="scope.rows">
            <div class="product-title" :title="scope.rows.title">
              {{ scope.rows.title }}
            </div>
            <div class="views-info" v-if="scope.rows.views !== undefined">
              <el-icon><View /></el-icon> {{ scope.rows.views || 0 }}
            </div>
          </div>
        </template>
        <template #price="scope">
          <template v-if="scope.rows && scope.rows.price !== undefined">
            <div class="price-container">
              <div class="current-price">¥{{ scope.rows.price.toFixed(2) }}</div>
              <div
                class="original-price"
                v-if="
                  scope.rows.originalPrice && scope.rows.originalPrice > scope.rows.price
                "
              >
                <s>¥{{ scope.rows.originalPrice.toFixed(2) }}</s>
                <el-tag size="small" type="danger" class="discount-tag">
                  {{ calculateDiscount(scope.rows.price, scope.rows.originalPrice) }}折
                </el-tag>
              </div>
            </div>
          </template>
          <template v-else>-</template>
        </template>
        <template #seller="scope">
          <template v-if="scope.rows && scope.rows.seller">
            <div class="seller-info">
              <el-avatar
                :size="24"
                :src="scope.rows.seller.avatar"
                class="seller-avatar"
                >{{ scope.rows.seller.username?.substring(0, 1) }}</el-avatar
              >
              <span class="seller-name">{{ scope.rows.seller.username }}</span>
            </div>
          </template>
          <template v-else>未知</template>
        </template>
        <template #status="scope">
          <template v-if="scope.rows && scope.rows.status">
            <el-tag :type="getStatusType(scope.rows.status)">
              {{ formatStatus(scope.rows.status) }}
            </el-tag>
            <el-button type="primary" link size="small" @click="handleReview(scope.rows)">
              审核
            </el-button>
          </template>
          <template v-else>-</template>
        </template>
        <template #operator="scope">
          <div class="action-buttons">
            <el-button type="primary" :icon="View" @click="handleView(scope.rows)"
              >查看</el-button
            >

            <el-button
              v-if="scope.rows.status !== '已下架'"
              type="danger"
              :icon="Delete"
              @click="handleRemove(scope.rows)"
              >下架</el-button
            >

            <el-button
              v-if="scope.rows.status === '已下架'"
              type="success"
              :icon="RefreshRight"
              @click="handleRestore(scope.rows)"
              >恢复</el-button
            >

            <el-dropdown>
              <el-button circle size="small">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="openProductLink(scope.rows)">
                    <el-icon><Link /></el-icon> 打开商品链接
                  </el-dropdown-item>
                  <el-dropdown-item @click="copyProductId(scope.rows)">
                    <el-icon><DocumentCopy /></el-icon> 复制商品ID
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click="contactSeller(scope.rows)"
                    v-if="scope.rows.seller && scope.rows.seller.email"
                  >
                    <el-icon><Message /></el-icon> 联系卖家
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </TableCustom>
    </div>
    <el-dialog title="查看详情" v-model="detailVisible" width="800px" destroy-on-close>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="商品信息" name="product">
          <TableDetail :data="viewData" :loading="detailLoading"></TableDetail>
        </el-tab-pane>
        <el-tab-pane label="卖家信息" name="seller">
          <TableDetail :data="sellerData" :loading="detailLoading"></TableDetail>
        </el-tab-pane>
        <el-tab-pane label="商品图片" name="images">
          <div v-if="productImages.length > 0" class="image-container">
            <el-image
              v-for="(img, index) in productImages"
              :key="index"
              :src="img"
              :preview-src-list="productImages"
              fit="cover"
              class="product-image"
            >
              <template #error>
                <div class="image-error">
                  <el-icon><icon-picture /></el-icon>
                  <span>加载失败</span>
                </div>
              </template>
            </el-image>
          </div>
          <el-empty v-else description="暂无图片"></el-empty>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
    <el-dialog title="商品审核" v-model="reviewVisible" width="500px" destroy-on-close>
      <el-form ref="reviewForm" :model="reviewForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(currentProduct.status)">
            {{ formatStatus(currentProduct.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态" prop="status">
          <el-select v-model="reviewForm.status" placeholder="请选择新状态">
            <el-option label="在售" value="在售"></el-option>
            <el-option label="已下架" value="已下架"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核理由" prop="reason">
          <el-input
            type="textarea"
            v-model="reviewForm.reason"
            placeholder="请输入审核理由（建议提供）"
            rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitReview" :loading="reviewLoading">
            确认
          </el-button>
          <el-button @click="reviewVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="下架商品" v-model="removeVisible" width="500px" destroy-on-close>
      <el-form ref="removeForm" :model="removeForm" label-width="100px">
        <el-form-item label="商品名称">
          <span>{{ currentProduct.title }}</span>
        </el-form-item>
        <el-form-item label="下架原因" prop="reason">
          <el-input
            type="textarea"
            v-model="removeForm.reason"
            placeholder="请输入下架原因（建议提供）"
            rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitRemove" :loading="removeLoading">
            确认下架
          </el-button>
          <el-button @click="removeVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Download,
  View,
  Delete,
  RefreshRight,
  Picture as IconPicture,
  Link,
  DocumentCopy,
  Message,
  MoreFilled,
} from "@element-plus/icons-vue";
import request from "@/utils/request";
import { FormOptionList } from "@/types/form-option";

// 导入组件
import TableCustom from "@/components/table-custom.vue";
import TableDetail from "@/components/table-detail.vue";
import TableSearch from "@/components/table-search.vue";

export default {
  name: "system-product",
  components: {
    TableCustom,
    TableDetail,
    TableSearch,
    Download,
    View,
    Delete,
    RefreshRight,
    IconPicture,
    Link,
    DocumentCopy,
    Message,
    MoreFilled,
  },
  setup() {
    // 查询相关
    const query = reactive({
      search: "",
      status: "",
      category: "",
      condition: "",
      minPrice: "",
      maxPrice: "",
      sort: "createdAt",
      order: "desc",
    });

    const searchOpt = ref<FormOptionList[]>([
      {
        type: "input",
        label: "搜索：",
        prop: "search",
        placeholder: "商品标题、描述",
      },
      {
        type: "select",
        label: "状态：",
        prop: "status",
        opts: [
          { label: "全部", value: "" },
          { label: "在售", value: "在售" },
          { label: "交易中", value: "交易中" },
          { label: "已售出", value: "已售出" },
          { label: "已下架", value: "已下架" },
        ],
      },
      {
        type: "select",
        label: "分类：",
        prop: "category",
        opts: [
          { label: "全部", value: "" },
          { label: "电子产品", value: "电子产品" },
          { label: "图书", value: "图书" },
          { label: "服装", value: "服装" },
          { label: "家居", value: "家居" },
          { label: "其他", value: "其他" },
        ],
      },
      {
        type: "select",
        label: "成色：",
        prop: "condition",
        opts: [
          { label: "全部", value: "" },
          { label: "全新", value: "全新" },
          { label: "几乎全新", value: "几乎全新" },
          { label: "二手良好", value: "二手良好" },
          { label: "二手一般", value: "二手一般" },
          { label: "二手较差", value: "二手较差" },
        ],
      },
      {
        type: "input",
        label: "最低价格：",
        prop: "minPrice",
        placeholder: "最低价格",
      },
      {
        type: "input",
        label: "最高价格：",
        prop: "maxPrice",
        placeholder: "最高价格",
      },
    ]);

    const handleSearch = () => {
      changePage(1);
    };

    // 表格相关
    const loading = ref(false);
    const columns = ref([
      { type: "index", label: "序号", width: 55, align: "center" },
      { prop: "image", label: "图片", slotName: "image", width: 80 },
      { prop: "title", label: "商品名称", slotName: "title", width: 180 },
      { prop: "price", label: "价格", slotName: "price", width: 120 },
      { prop: "category", label: "分类", width: 100 },
      { prop: "condition", label: "成色", width: 100 },
      {
        prop: "seller",
        label: "卖家",
        slotName: "seller",
        width: 120,
      },
      {
        prop: "status",
        label: "状态",
        slotName: "status",
        width: 180,
      },
      {
        prop: "createdAt",
        label: "发布时间",
        formatter: (val: any) => {
          return new Date(val).toLocaleString();
        },
        width: 180,
      },
      { prop: "operator", label: "操作", width: 250 },
    ]);

    // 状态格式化
    const formatStatus = (status: string) => {
      return status || "未知";
    };

    // 获取状态对应的标签类型
    const getStatusType = (status: string) => {
      const typeMap: Record<string, string> = {
        在售: "success",
        交易中: "warning",
        已售出: "info",
        已下架: "danger",
      };
      return typeMap[status] || "";
    };

    // 判断是否有激活的筛选条件
    const hasActiveFilters = computed(() => {
      return (
        !!query.search ||
        !!query.status ||
        !!query.category ||
        !!query.condition ||
        !!query.minPrice ||
        !!query.maxPrice
      );
    });

    // 清除单个筛选条件
    const clearFilter = (field: string) => {
      query[field] = "";
      getData();
    };

    // 清除价格筛选
    const clearPriceFilter = () => {
      query.minPrice = "";
      query.maxPrice = "";
      getData();
    };

    // 重置所有筛选条件
    const resetFilters = () => {
      Object.keys(query).forEach((key) => {
        if (key !== "sortBy" && key !== "sortOrder") {
          query[key] = "";
        }
      });
      getData();
    };

    // 工具函数 - 计算折扣
    const calculateDiscount = (price: number, originalPrice: number) => {
      if (!originalPrice || originalPrice <= 0 || !price || price <= 0) {
        return 10;
      }
      const discount = (price / originalPrice) * 10;
      return discount.toFixed(1);
    };

    // 工具函数 - 打开商品链接
    const openProductLink = (product: any) => {
      if (!product || !product._id) {
        ElMessage.warning("商品信息不完整，无法打开链接");
        return;
      }
      // 这里应该替换为实际的商品链接
      const productUrl = `http://localhost:8080/product/${product._id}`;
      window.open(productUrl, "_blank");
      ElMessage.success("已在新窗口打开商品链接");
    };

    // 工具函数 - 复制商品ID
    const copyProductId = (product: any) => {
      if (!product || !product._id) {
        ElMessage.warning("无法获取商品ID");
        return;
      }

      // 使用clipboard API复制
      navigator.clipboard
        .writeText(product._id)
        .then(() => {
          ElMessage.success("商品ID已复制");
        })
        .catch(() => {
          ElMessage.error("复制失败，请手动复制");
        });
    };

    // 工具函数 - 联系卖家
    const contactSeller = (product: any) => {
      if (!product || !product.seller || !product.seller.email) {
        ElMessage.warning("无法获取卖家联系方式");
        return;
      }
      const subject = `关于您在平台上发布的商品「${product.title || ""}」`;
      const mailtoLink = `mailto:${product.seller.email}?subject=${encodeURIComponent(
        subject
      )}`;
      window.open(mailtoLink);
      ElMessage.success("已打开邮件客户端");
    };

    const page = reactive({
      index: 1,
      size: 10,
      total: 0,
    });

    const tableData = ref<any[]>([]);

    const getData = async () => {
      try {
        loading.value = true;
        const params = {
          page: page.index,
          limit: page.size,
          ...query,
        };

        const res = await request.get("/api/products/admin/products", params);
        if (res.success) {
          tableData.value = res.data.products || [];
          page.total = res.data.total || 0;
        } else {
          ElMessage.error(res.message || "获取商品列表失败");
        }
      } catch (error) {
        console.error("获取商品列表失败:", error);
        ElMessage.error("获取商品列表失败");
      } finally {
        loading.value = false;
      }
    };

    const changePage = (val: number) => {
      page.index = val;
      getData();
    };

    // 导出商品
    const exportProducts = () => {
      ElMessageBox.confirm("确定要导出当前筛选条件下的商品数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          ElMessage.success("导出成功");
          // 这里可以添加实际的导出逻辑
        })
        .catch(() => {});
    };

    // 查看详情弹窗相关
    const detailVisible = ref(false);
    const detailLoading = ref(false);
    const activeTab = ref("product");
    const viewData = ref({
      row: {},
      list: [],
    });
    const sellerData = ref({
      row: {},
      list: [],
    });
    const productImages = ref<string[]>([]);

    const handleView = async (row: any) => {
      try {
        detailLoading.value = true;
        detailVisible.value = true;
        activeTab.value = "product";
        productImages.value = [];

        // 获取商品详情
        const res = await request.get(`/api/products/admin/products/${row._id}`);

        if (res.success) {
          const productDetail = res.data.product || res.data;
          viewData.value.row = { ...productDetail };
          viewData.value.list = [
            { prop: "_id", label: "商品ID" },
            { prop: "title", label: "标题" },
            { prop: "description", label: "描述" },
            {
              prop: "price",
              label: "价格",
              formatter: (val: number) => `¥${val.toFixed(2)}`,
            },
            {
              prop: "originalPrice",
              label: "原价",
              formatter: (val: number) => (val ? `¥${val.toFixed(2)}` : "未设置"),
            },
            { prop: "category", label: "分类" },
            { prop: "condition", label: "成色" },
            { prop: "status", label: "状态" },
            { prop: "adminRemark", label: "管理员备注" },
            { prop: "views", label: "浏览量" },
            {
              prop: "createdAt",
              label: "发布时间",
              formatter: (val: string) => new Date(val).toLocaleString(),
            },
            {
              prop: "updatedAt",
              label: "更新时间",
              formatter: (val: string) =>
                val ? new Date(val).toLocaleString() : "未更新",
            },
          ];

          // 处理卖家信息
          if (productDetail.seller) {
            const seller = productDetail.seller;
            sellerData.value.row = { ...seller };
            sellerData.value.list = [
              { prop: "_id", label: "卖家ID" },
              { prop: "username", label: "用户名" },
              { prop: "email", label: "邮箱" },
              { prop: "phone", label: "联系电话" },
              { prop: "studentId", label: "学号/工号" },
              { prop: "status", label: "账号状态" },
            ];
          }

          // 处理商品图片
          if (
            productDetail.images &&
            Array.isArray(productDetail.images) &&
            productDetail.images.length > 0
          ) {
            productImages.value = productDetail.images;
          }
        } else {
          ElMessage.error(res.message || "获取商品详情失败");
          detailVisible.value = false;
        }
      } catch (error) {
        console.error("获取商品详情失败:", error);
        ElMessage.error("获取商品详情失败");
        detailVisible.value = false;
      } finally {
        detailLoading.value = false;
      }
    };

    // 下架商品相关
    const removeVisible = ref(false);
    const removeLoading = ref(false);
    const currentProduct = ref<any>({});
    const removeForm = reactive({
      reason: "",
    });

    const handleRemove = (row: any) => {
      currentProduct.value = { ...row };
      removeForm.reason = "";
      removeVisible.value = true;
    };

    const submitRemove = async () => {
      try {
        removeLoading.value = true;
        const res = await request.put(
          `/api/products/admin/products/${currentProduct.value._id}/remove`,
          removeForm
        );
        if (res.success) {
          ElMessage.success("商品下架成功");
          removeVisible.value = false;
          getData(); // 刷新数据
        } else {
          ElMessage.error(res.message || "商品下架失败");
        }
      } catch (error) {
        console.error("商品下架失败:", error);
        ElMessage.error("商品下架失败");
      } finally {
        removeLoading.value = false;
      }
    };

    // 审核商品相关
    const reviewVisible = ref(false);
    const reviewLoading = ref(false);
    const reviewForm = reactive({
      status: "",
      reason: "",
    });

    const handleReview = (row: any) => {
      currentProduct.value = { ...row };
      reviewForm.status = row.status;
      reviewForm.reason = "";
      reviewVisible.value = true;
    };

    const handleRestore = (row: any) => {
      currentProduct.value = { ...row };
      reviewForm.status = "在售";
      reviewForm.reason = "管理员恢复商品";
      submitReview();
    };

    const submitReview = async () => {
      if (!reviewForm.status) {
        ElMessage.warning("请选择新状态");
        return;
      }

      try {
        reviewLoading.value = true;
        const res = await request.put(
          `/api/products/admin/products/${currentProduct.value._id}/review`,
          reviewForm
        );
        if (res.success) {
          ElMessage.success("商品审核成功");
          reviewVisible.value = false;
          getData(); // 刷新数据
        } else {
          ElMessage.error(res.message || "商品审核失败");
        }
      } catch (error) {
        console.error("商品审核失败:", error);
        ElMessage.error("商品审核失败");
      } finally {
        reviewLoading.value = false;
      }
    };

    onMounted(() => {
      getData();
    });

    return {
      query,
      searchOpt,
      handleSearch,
      loading,
      columns,
      page,
      tableData,
      getData,
      changePage,
      exportProducts,
      detailVisible,
      detailLoading,
      viewData,
      handleView,
      formatStatus,
      getStatusType,
      removeVisible,
      removeLoading,
      currentProduct,
      removeForm,
      handleRemove,
      submitRemove,
      reviewVisible,
      reviewLoading,
      reviewForm,
      handleReview,
      handleRestore,
      submitReview,
      Download,
      View,
      Delete,
      RefreshRight,
      IconPicture,
      activeTab,
      sellerData,
      productImages,
      calculateDiscount,
      openProductLink,
      copyProductId,
      contactSeller,
      hasActiveFilters,
      clearFilter,
      clearPriceFilter,
      resetFilters,
    };
  },
};
</script>

<style scoped>
.container {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.price {
  color: #ff6b6b;
  font-weight: bold;
}

.price-container {
  display: flex;
  flex-direction: column;
}

.current-price {
  color: #ff6b6b;
  font-weight: bold;
}

.original-price {
  margin-top: 4px;
  font-size: 12px;
  color: #999;
  display: flex;
  align-items: center;
}

.discount-tag {
  margin-left: 5px;
  transform: scale(0.8);
  transform-origin: left;
}

.product-title {
  font-weight: bold;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
}

.views-info {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  display: flex;
  align-items: center;
}

.views-info .el-icon {
  margin-right: 4px;
  font-size: 14px;
}

.seller-info {
  display: flex;
  align-items: center;
}

.seller-avatar {
  margin-right: 5px;
}

.seller-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 70px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.product-image {
  width: 200px;
  height: 200px;
  border-radius: 5px;
  border: 1px solid #eee;
  transition: all 0.3s;
}

.product-image:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
  height: 100%;
}

.filter-tags {
  margin: 10px 0;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 5px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.filter-label {
  margin-right: 10px;
  font-weight: bold;
  color: #606266;
}

.filter-tag {
  margin-right: 10px;
  margin-bottom: 5px;
}
</style>
